package com.backom.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.backom.domain.User;


@Repository
public class UserDao {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public int getMatchCount(String userName, String password) {
		
		String sql = "select count(*) from t_user where user_name=? and passwor=?";
		return jdbcTemplate.queryForInt(sql, new Object[]{userName,password});
	}
	
	public User findUserByUserName(final String userName) {
		String sqlStr = "select usre_id,user_name,credits "
				+ " FROM t_user where user_name = ?";
		final User user = new User();
		jdbcTemplate.query(sqlStr, new Object[]{userName}, new RowCallbackHandler() {
			
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				// TODO Auto-generated method stub
				user.setUserId(rs.getInt("user_id"));
				user.setUserName(userName);
				user.setCredits(rs.getInt("credits"));
				
			}
		});
		return user;
	}
	
	public void updateLoginInfo(User user) {
		String sqlStr = "update t_user set lastip=?,lastvisit=?,credits=? where user_id=?";
		jdbcTemplate.update(sqlStr, new Object[]{user.getLastIp(),user.getLastVisit(),user.getCredits(),user.getUserId()});
	}

}
